'use strict';
const { formatUser } = require("../utils/formatUser");
module.exports = app => {
  class userRelationService extends app.Service {

    // 通过FollowerId查找用户
    async getUsersByFollowerId(followerId) {
      const result = await this.app.model.User.findAndCountAll({
        attributes: ['id', 'userName', 'nickName', 'avatar'],
        limit: 50,
        offset: 0,
        order: [['id', 'desc']],
        include: {
          model: this.app.model.UserRelation,
          where: {
            followerId,
            userId: {
              // Sequelize 中的不等于 ne -> no equal
              [app.Sequelize.Op.ne]: followerId,
            }
          },
        },
      });
      // result 中count,rows
      // 格式化用户信息
      const userList = formatUser(result.rows.map(item => item.dataValues));
      return {
        count: result.count,
        userList,
      }
    }
    // 获取关注人列表
    async getFollower(userId) {
      const result = await this.ctx.model.UserRelation.findAndCountAll({
        limit: 50,
        offset: 0,
        order: [["id", 'desc']],
        include: {
          model: this.app.model.User,
          attributes: ['id', 'userName', 'nickName', 'avatar'],
        },
        where: {
          userId,
          followerId: {
            // Sequelize 中的不等于 ne -> no equal
            [app.Sequelize.Op.ne]: userId,
          }
        },
      });
      // rows的结构 = [{userId,followerId, user:{dataValues}}]
      let userList = result.rows.map(item => item.dataValues);
      // 格式化用户信息
      userList = userList.map(item => {
        let user = item.user.dataValues;
        return formatUser(user)
      });
      console.log(userList)
      return {
        count: result.count,
        userList,
      }
    }
    // 添加关注
    async addFollower(userId, followerId) {
      // 向数据库中添加
      const result = await this.app.model.UserRelation.create({ userId, followerId, });
      return result;
    }
    // 取消关注
    async noFollower(userId, followerId) {
      const result = await this.app.model.UserRelation.destroy({
        where: {
          userId,
          followerId,
        }
      });
      return result > 0;
    }
  }
  return userRelationService;
};

